﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

public class XmlSerializeHelper
{
    /// <summary>
    /// 对象序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="obj"></param>
	public static void SaveXmlFormObject<T>(string path, T obj)
    {
        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            xs.Serialize(fs, obj);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="xml"></param>
    /// <returns></returns>
    public static T LoadObjectFromXmlString<T>(string xml)
    {
        var serializer = new XmlSerializer(typeof(T));
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            return (T)serializer.Deserialize(ms);
        }
    }

    public static T LoadObjectFromXml<T>(string file)
    {
        if (!File.Exists(file))
        {
            return default(T);
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(file);
        return LoadObjectFromXmlString<T>(doc.InnerXml);
    }
}
